package com.hngtrust.iir.risk.controller;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.hngtrust.clickhouse.news.entity.AppNews;
import com.hngtrust.clickhouse.news.entity.AppNewsSentiment;
import com.hngtrust.clickhouse.news.service.AppNewsSentimentService;
import com.hngtrust.clickhouse.news.service.AppNewsService;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.controller.vo.OptLogReqVO;
import com.hngtrust.iir.base.entity.Dict;
import com.hngtrust.iir.base.service.DictService;
import com.hngtrust.iir.base.service.LogService;
import com.hngtrust.iir.company.dto.DefaultMonitorListDTO;
import com.hngtrust.iir.company.dto.HomePageDynamicRespVO;
import com.hngtrust.iir.company.dto.ListRiskRespDTO;
import com.hngtrust.iir.company.dto.QueryHomePageCompDTO;
import com.hngtrust.iir.company.dto.QueryParticularsDTO;
import com.hngtrust.iir.company.entity.CompDept;
import com.hngtrust.iir.company.entity.CompRisk;
import com.hngtrust.iir.company.service.CompDeptService;
import com.hngtrust.iir.company.service.CompRiskService;
import com.hngtrust.iir.company.service.CompanyService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.elk.exception.ElkErrorType;
import com.hngtrust.iir.elk.exception.ElkException;
import com.hngtrust.iir.news.controller.dto.ListNewsRespVO;
import com.hngtrust.iir.report.controller.dto.QueryListSchemeVO;
import com.hngtrust.iir.risk.controller.dto.AddListMonitorReqVO;
import com.hngtrust.iir.risk.controller.dto.CancelMonitorVO;
import com.hngtrust.iir.risk.controller.dto.CompRiskVO;
import com.hngtrust.iir.risk.controller.dto.DefaultMonitorListRespVO;
import com.hngtrust.iir.risk.controller.dto.DeleteMonitorSchemeReqVO;
import com.hngtrust.iir.risk.controller.dto.EditMonitorSchemeReqVO;
import com.hngtrust.iir.risk.controller.dto.EdtMonitorReqVO;
import com.hngtrust.iir.risk.controller.dto.ExcelDownDefaultListVO;
import com.hngtrust.iir.risk.controller.dto.ExcelListMonitorRespVO;
import com.hngtrust.iir.risk.controller.dto.HomePageNewsCarouselVRespVO;
import com.hngtrust.iir.risk.controller.dto.HomePageNewsRespVO;
import com.hngtrust.iir.risk.controller.dto.HomePageNewsTrendVO;
import com.hngtrust.iir.risk.controller.dto.HomePageRiskReqVO;
import com.hngtrust.iir.risk.controller.dto.HomePageRiskRespVO;
import com.hngtrust.iir.risk.controller.dto.ListMonitorReqVO;
import com.hngtrust.iir.risk.controller.dto.ListMonitorRespVO;
import com.hngtrust.iir.risk.controller.dto.ListRiskNewsReqVO;
import com.hngtrust.iir.risk.controller.dto.ListRiskReqVO;
import com.hngtrust.iir.risk.controller.dto.ListSchemeConfigReqVO;
import com.hngtrust.iir.risk.controller.dto.MonitorCompReqVO;
import com.hngtrust.iir.risk.controller.dto.QueryByCompIdVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompAssociateRiskReqVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompMonitorReqVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompMonitorRespVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompNewsReqVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompRiskReqVO;
import com.hngtrust.iir.risk.controller.dto.QueryCompRiskTypeRespVO;
import com.hngtrust.iir.risk.controller.dto.RiskHomeNewsCompRespVO;
import com.hngtrust.iir.risk.controller.dto.RiskHomePageCompRespVO;
import com.hngtrust.iir.risk.controller.dto.RiskHomePageLevelVO;
import com.hngtrust.iir.risk.controller.dto.RiskHomePageReqVO;
import com.hngtrust.iir.risk.controller.dto.RiskHomePageRespVO;
import com.hngtrust.iir.risk.controller.dto.RiskSchemeConfigReqVO;
import com.hngtrust.iir.risk.controller.dto.RiskTrendVO;
import com.hngtrust.iir.risk.dto.ListRiskMonitorDTO;
import com.hngtrust.iir.risk.dto.ListRiskTypeReqDTO;
import com.hngtrust.iir.risk.dto.QueryByRiskTypeRespDTO;
import com.hngtrust.iir.risk.dto.QueryBySchemeIdReqDTO;
import com.hngtrust.iir.risk.dto.QueryCompAssociateDTO;
import com.hngtrust.iir.risk.dto.RiskTimeDTO;
import com.hngtrust.iir.risk.entity.RiskMonitor;
import com.hngtrust.iir.risk.entity.RiskMonitorScheme;
import com.hngtrust.iir.risk.entity.RiskSchemeConfig;
import com.hngtrust.iir.risk.service.ExcelDownloadService;
import com.hngtrust.iir.risk.service.RiskCompService;
import com.hngtrust.iir.risk.service.RiskMonitorSchemeService;
import com.hngtrust.iir.risk.service.RiskMonitorService;
import com.hngtrust.iir.risk.service.RiskSchemeConfigService;
import com.hngtrust.iir.risk.service.RiskTypeService;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.user.service.UserService;
import com.hngtrust.iir.util.DateUtils;
import com.hngtrust.iir.util.ListUtil;
import com.tiger.web.annotation.DownloadMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 风险预警管理
 *
 * @author Keqiwei
 * @date 2021/3/30 15:40
 */
@Slf4j
@Api(tags = "风险预警管理")
@RestController
@RequestMapping("/risk")
public class RiskController {
    
    @Autowired
    private RiskMonitorService monitorService;
    
    @Autowired
    private RiskMonitorSchemeService schemeService;
    
    @Autowired
    private AppNewsService newsService;
    
    @Autowired
    private CompRiskService riskService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CompDeptService compDeptService;
    
    @Autowired
    private MyIdGenerator myIdGenerator;
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private RiskSchemeConfigService configService;
    
    @Autowired
    private TagRelService tagRelService;
    
   @Autowired
   private ExcelDownloadService excelDownloadSevice;
    
    @Autowired
    private RiskTypeService riskTypeService;
    
    @Autowired
    private CompRiskService compRiskService;
    
    @Autowired
    private DictService dictService;
    
    @Autowired
    private RiskCompService riskCompService;
    
    @Autowired
    private AppNewsSentimentService appNewsSentimentService;
    
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private RiskMonitorService riskMonitorService;
    
    @Autowired
    private LogService logService;
    
    
    @Value("${tiger.minio.out.address}")
    private String minioAddress;
    
    @ApiOperation("监控列表")
    @PostMapping("/list-monitor")
    public ResponseInfo<PageResult<ListMonitorRespVO>> listMonitor(@ApiParam("监控列表请求") @Valid @RequestBody ReqDTO<ListMonitorReqVO> reqDTO){
        ListRiskMonitorDTO dto  = new ListRiskMonitorDTO();
        BeanUtils.copyProperties(reqDTO.getContent(),dto);
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        
        dto.setCreatUserId(loginUser.getId());
        PageResult<RiskMonitor> page = pageService.page(reqDTO.getPageParam(), () -> monitorService.queryListMonitor(dto));
        List<ListMonitorRespVO> list = new ArrayList<>();
        for (RiskMonitor monitor:page.getRows()){
            ListMonitorRespVO vo = new ListMonitorRespVO();
            BeanUtils.copyProperties(monitor,vo);
            vo.setSchemeName(schemeService.queryById(monitor.getSchemeId()).getName());
            vo.setCreateUserName(userService.queryById(monitor.getCreateUserId()).getName());
            CompRisk compRisk = compRiskService.queryByCompId(monitor.getCompId());
            List<Date> dates = appNewsSentimentService.queryDate(monitor.getCompId().toString());
            vo.setNews(appNewsSentimentService.countNewsByCompId(String.valueOf(monitor.getCompId())));
            vo.setRisk(riskService.countRiskByCompId(monitor.getCompId()));
            if(null != compRisk){
                dates.add(compRisk.getBuildTime());
            }
            if(!dates.isEmpty()){
                List<Date> times = dates.stream().filter(Objects::nonNull).sorted((a, b) -> -a.compareTo(b)).collect(Collectors.toList());
                if(!times.isEmpty()){
                    vo.setBuildTime(times.get(0));
                }
            }
            if("0".equals(vo.getRisk()) && "0".equals(vo.getNews())){
                vo.setBuildTime(null);
            }
            list.add(vo);
        }
        PageResult<ListMonitorRespVO> pageResult = new PageResult<>();
        pageResult.setPage(page.getPage());
        pageResult.setRows(list);
        OptLogReqVO vo = new OptLogReqVO();
        vo.setStatus(1);
        vo.setOptContent("搜索自定义监控，时间筛选：:"+reqDTO.getContent().getCreateStartTime()+reqDTO.getContent().getCreateStartTime()+"+关键字:"+reqDTO.getContent().getCompName());
        vo.setOptModule(6);
        vo.setOptType(3);
        logService.saveOptLog(vo);
        
        return new ResponseInfo<>(pageResult);
    }
    
    
    @ApiOperation("下载监控列表")
    @DownloadMapping("/down-monitor-list")
    public void downMonitorList(@ApiParam("监控列表请求") @Valid ListMonitorReqVO reqDTO,HttpServletResponse response)
            throws Exception {
        ListRiskMonitorDTO dto  = new ListRiskMonitorDTO();
        BeanUtils.copyProperties(reqDTO,dto);
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        List<ExcelListMonitorRespVO> result = new ArrayList<>();
        dto.setCreatUserId(loginUser.getId());
        List<RiskMonitor> riskMonitors = monitorService.queryListMonitor(dto);
        for (RiskMonitor monitor:riskMonitors){
            ListMonitorRespVO vo = new ListMonitorRespVO();
            BeanUtils.copyProperties(monitor,vo);
            vo.setSchemeName(schemeService.queryById(monitor.getSchemeId()).getName());
            vo.setCreateUserName(userService.queryById(monitor.getCreateUserId()).getName());
            CompRisk compRisk = compRiskService.queryByCompId(monitor.getCompId());
            List<Date> dates = appNewsSentimentService.queryDate(monitor.getCompId().toString());
            vo.setNews(appNewsSentimentService.countNewsByCompId(String.valueOf(monitor.getCompId())));
            vo.setRisk(riskService.countRiskByCompId(monitor.getCompId()));
            if(null != compRisk){
                dates.add(compRisk.getBuildTime());
            }
            if(!dates.isEmpty()){
                List<Date> times = dates.stream().filter(Objects::nonNull).sorted((a, b) -> -a.compareTo(b)).collect(Collectors.toList());
                if(!times.isEmpty()){
                    vo.setBuildTime(times.get(0));
                }
            }
            ExcelListMonitorRespVO respVO = new ExcelListMonitorRespVO();
            BeanUtils.copyProperties(vo,respVO);
            respVO.setBuildTime(DateUtils.format(vo.getBuildTime(),DateUtils.DATE));
            respVO.setCreateTime(DateUtils.format(vo.getCreateTime(),DateUtils.DATE));
            result.add(respVO);
        }
        if (result.isEmpty()){
            result.add(new ExcelListMonitorRespVO());
        }
    
        OptLogReqVO vo = new OptLogReqVO();
        vo.setStatus(1);
        vo.setOptModule(6);
        vo.setOptType(11);
        vo.setOptContent("导出自定义监控列表");
        logService.saveOptLog(vo);
        excelDownloadSevice.excelDownload(result, response, "自定义监控列表");
        
    }
    
    @ApiOperation("取消监控")
    @PostMapping("/cancel-monitor")
    public ResponseInfo<Object> cancelMonitor(@ApiParam("请求参数") @Valid @RequestBody CancelMonitorVO vo){
        RiskMonitor riskMonitor = new RiskMonitor();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        riskMonitor.setCompId(vo.getCompId());
        riskMonitor.setStatus(Constant.DEFAULT_STATUS_DELETE);
        riskMonitor.setCreateUserId(loginUser.getId());
        monitorService.modify(riskMonitor);
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setOptModule(6);
        vo1.setOptType(15);
        vo1.setOptContent("取消"+companyService.queryById(vo.getCompId())+"监控");
        vo1.setStatus(1);
        logService.saveOptLog(vo1);
        
        
        return new ResponseInfo<>();
    }
    
    
    @ApiOperation("添加监控")
    @PostMapping("/add-monitor")
    public ResponseInfo<Object> addMonitor(@ApiParam("添加监控请求") @Valid @RequestBody MonitorCompReqVO vo){
        
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        RiskMonitor riskMonitor = new RiskMonitor();
        riskMonitor.setCompId(vo.getCompId());
        riskMonitor.setCompName(vo.getCompName());
        riskMonitor.setCreateUserId(loginUser.getId());
        ResponseInfo<Object> info = new ResponseInfo<Object>();
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setOptType(6);
        vo1.setOptModule(6);
        List<RiskMonitor> riskMonitors = monitorService.queryList(riskMonitor);
        if (riskMonitors.isEmpty()) {
            RiskMonitor monitor= new RiskMonitor();
            monitor.setCreateUserId(loginUser.getId());
            monitor.setCompId(vo.getCompId());
            monitor.setCompName(vo.getCompName());
            monitor.setCreateTime(new Date());
            monitor.setUpdateUserId(loginUser.getId());
            monitor.setUpdateTime(new Date());
            monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
            monitor.setSchemeId(vo.getSchemeId());
            monitor.setId(myIdGenerator.nextId());
            monitorService.add(monitor);
            info.setMessage("添加成功");
            vo1.setStatus(1);
            vo1.setOptContent("添加监控"+monitor.getCompName());
        }else{
            if(riskMonitors.get(0).getStatus() == 1){
                riskMonitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
                if(null != vo.getSchemeId()){
                    riskMonitor.setSchemeId(vo.getSchemeId());
                }
                monitorService.modify(riskMonitor);
                info.setMessage("添加成功");
                return info;
            }
            info.setMessage("该公司已添加");
            info.setCode("1");
            vo1.setStatus(1);
            vo1.setOptContent("添加监控失败");
        }
        logService.saveOptLog(vo1);
       return info;
    }
    
    @ApiOperation("批量添加监控")
    @PostMapping("/add-list-monitor")
    public ResponseInfo<Object> addListMonitor(@ApiParam("请求参数") @Valid @RequestBody AddListMonitorReqVO vo){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        for (AddListMonitorReqVO.Comp comp : vo.getCompList()) {
            RiskMonitor monitor= new RiskMonitor();
            monitor.setCreateUserId(loginUser.getId());
            monitor.setCompId(comp.getCompId());
            monitor.setCompName(comp.getCompName());
            monitor.setCreateTime(new Date());
            monitor.setUpdateUserId(loginUser.getId());
            monitor.setUpdateTime(new Date());
            monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
            monitor.setSchemeId(vo.getSchemeId());
            monitor.setId(myIdGenerator.nextId());
            monitorService.add(monitor);
        }
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setOptType(6);
        vo1.setOptModule(6);
        vo1.setStatus(1);
        vo1.setOptContent("添加监控"+vo.getCompList().get(0).getCompName());
        return new ResponseInfo();
    }
    
    
    @ApiOperation("删除监控")
    @PostMapping("/delete-monitor")
    public ResponseInfo<Object> deleteMonitor(@ApiParam("删除监控") @Valid @RequestBody EdtMonitorReqVO vo){
        if(null != vo.getId() && vo.getId() > 0){
            monitorService.deleteById(vo.getId());
        }
        else if(null != vo.getCompId() && vo.getCompId() > 0){
            RiskMonitor riskMonitor = new RiskMonitor();
            riskMonitor.setCompId(vo.getCompId());
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            riskMonitor.setCreateUserId(loginUser.getId());
            List<RiskMonitor> list = monitorService.queryList(riskMonitor);
            for(RiskMonitor obj : list){
                monitorService.deleteById(obj.getId());
            }
        }
        
        return new ResponseInfo<Object>();
    }
    
    @ApiOperation("编辑监控")
    @PostMapping("/update-monitor")
    public ResponseInfo<Object> updateMonitor(@ApiParam("监控参数") @Valid @RequestBody EdtMonitorReqVO vo){
        RiskMonitor monitor = new RiskMonitor();
        BeanUtils.copyProperties(vo,monitor);
        monitor.setUpdateTime(new Date());
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        monitor.setUpdateUserId(loginUser.getId());
        monitorService.modifyById(monitor);
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptContent("修改"+companyService.queryById(vo.getCompId()).getName()+"监控方案");
        vo1.setOptType(7);
        vo1.setOptModule(6);
        logService.saveOptLog(vo1);
        
        return new ResponseInfo<Object>();
    }
    
  
    
    @ApiOperation("监控方案列表")
    @PostMapping("/list-monitor-scheme")
    public ResponseInfo<PageResult<RiskMonitorScheme>> listMonitorScheme(@ApiParam("分页参数") @Valid @RequestBody ReqDTO<QueryListSchemeVO> dto){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        PageResult<RiskMonitorScheme> page = pageService
                .page(dto.getPageParam(), () -> schemeService.queryListScheme(loginUser.getId(),dto.getContent().getStatus()));
        return new ResponseInfo<>(page);
    }
    
    @ApiOperation("添加监控方案")
    @PostMapping("/add-monitor-scheme")
    public ResponseInfo<String> addMonitorScheme(@ApiParam("添加参数") @Valid @RequestBody EditMonitorSchemeReqVO vo){
        
        RiskMonitorScheme scheme = new RiskMonitorScheme();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        scheme.setName(vo.getName());
        scheme.setCreateUserId(loginUser.getId());
        
        if (!schemeService.query(scheme).isEmpty()) {
            ResponseInfo<String> info  = new ResponseInfo<>();
            info.setMessage("方案名已存在");
            info.setCode("1");
            return info;
        }
        scheme.setCreateUserId(loginUser.getId());
        scheme.setCreateTime(new Date());
        scheme.setUpdateTime(new Date());
        scheme.setUpdateUserId(loginUser.getId());
        scheme.setId(myIdGenerator.nextId());
        scheme.setName(vo.getName());
        scheme.setStatus(0);
        scheme.setNote(vo.getNote());
        schemeService.add(scheme);
        return new ResponseInfo<>();
    }
    
    @ApiOperation("编辑监控方案")
    @PostMapping("/update-monitor-scheme")
    public ResponseInfo<Object> updateMonitorScheme(@ApiParam("添加参数") @Valid @RequestBody EditMonitorSchemeReqVO vo){
        RiskMonitorScheme scheme = new RiskMonitorScheme();
        scheme.setName(vo.getName());
        scheme.setId(vo.getId());
        ResponseInfo<Object> info = new ResponseInfo<>();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        scheme.setCreateUserId(loginUser.getId());
        if (!schemeService.query(scheme).isEmpty()) {
            info.setMessage("方案名已存在");
            info.setCode("1");
            return info;
        }
        scheme.setUpdateTime(new Date());
        scheme.setId(vo.getId());
        scheme.setUpdateUserId(loginUser.getId());
        scheme.setNote(vo.getNote());
        if(vo.getNote() != null && !vo.getNote().equals("")){
            schemeService.modifyById(scheme);
        }else{
            schemeService.modifyByIdNote(scheme);
        }
    
        return info;
    }
    
    @ApiOperation("删除和禁用监控方案")
    @PostMapping("/delete-monitor-scheme")
    public ResponseInfo<Object> deleteMonitorScheme(@ApiParam("删除参数") @Valid @RequestBody DeleteMonitorSchemeReqVO vo) {
        RiskMonitor monitor = new RiskMonitor();
        monitor.setSchemeId(vo.getId());
        ResponseInfo<Object> info = new ResponseInfo<Object>();
        if (monitorService.queryList(monitor).isEmpty()) {
            RiskMonitorScheme scheme = new RiskMonitorScheme();
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            scheme.setUpdateUserId(loginUser.getId());
            scheme.setUpdateTime(new Date());
            scheme.setId(vo.getId());
            scheme.setStatus(vo.getStatus());
            schemeService.modifyById(scheme);
            info.setData("成功");
            return info;
        }
        info.setMessage("监控中有公司，禁止操作");
        info.setCode("1");
        return info;
    }
    
    @ApiOperation("监控方案配置")
    @PostMapping("/risk-scheme-config")
    public ResponseInfo<Object> riskSchemeConfig(@ApiParam("添加参数") @Valid @RequestBody RiskSchemeConfigReqVO vo){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        for (Long tagId : vo.getRisk()) {
            RiskSchemeConfig config = new RiskSchemeConfig();
            config.setCreateUserId(loginUser.getId());
            config.setCreateTime(new Date());
            config.setTagClass(Constant.SCHEME_CONFIG_RISK);
            config.setTagId(tagId);
            config.setId(myIdGenerator.nextId());
            config.setSchemeId(vo.getSchemeId());
            configService.add(config);
        }
        for (Long tagId : vo.getNews()) {
            RiskSchemeConfig config = new RiskSchemeConfig();
            config.setCreateUserId(loginUser.getId());
            config.setCreateTime(new Date());
            config.setTagClass(Constant.SCHEME_CONFIG_NEWS);
            config.setTagId(tagId);
            config.setId(myIdGenerator.nextId());
            config.setSchemeId(vo.getSchemeId());
            configService.add(config);
        }
        return new ResponseInfo<Object>();
    }
    
    @ApiOperation("监控方案配置列表")
    @PostMapping("/list-scheme-config")
    public ResponseInfo<List<Long>> listSchemeConfig(@ApiParam("查询参数") @Valid @RequestBody ListSchemeConfigReqVO vo){
        QueryBySchemeIdReqDTO dto = new QueryBySchemeIdReqDTO();
        dto.setSchemeIds(Arrays.asList(vo.getSchemeId()));
        dto.setTagClass(vo.getTagClass());
        List<Long> tagIds = configService.queryTagIdBySchemeId(dto);
        return new ResponseInfo<List<Long>>(tagIds);
    }
    
    @ApiOperation("修改监控方案配置")
    @PostMapping("/update-scheme-config")
    public ResponseInfo<Object> updateSchemeConfig(@ApiParam("修改参数") @Valid @RequestBody RiskSchemeConfigReqVO vo){
        configService.deleteBySchemeId(vo.getSchemeId());
        for (Long tagId : vo.getRisk()) {
            RiskSchemeConfig config = new RiskSchemeConfig();
            config.setTagClass(Constant.SCHEME_CONFIG_RISK);
            config.setTagId(tagId);
            config.setSchemeId(vo.getSchemeId());
            config.setId(myIdGenerator.nextId());
            configService.add(config);
        }
        for (Long tagId : vo.getNews()) {
            RiskSchemeConfig config = new RiskSchemeConfig();
            config.setTagClass(Constant.SCHEME_CONFIG_NEWS);
            config.setTagId(tagId);
            config.setSchemeId(vo.getSchemeId());
            config.setId(myIdGenerator.nextId());
            configService.add(config);
        }
        return new ResponseInfo<>();
    }
    
    @ApiOperation("风险预警详情")
    @PostMapping("/list-risk-particulars")
    public ResponseInfo<PageResult<ListRiskRespDTO>> listRiskParticulars(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<ListRiskReqVO> reqDTO){
        log.error("查询标签"+reqDTO.getContent().getSchemeIds().size());
        PageResult<ListRiskRespDTO> page = new PageResult<>();
        List<Long> compIds = new ArrayList<>();
        List<Long> tagIds = new ArrayList<>();
        if(reqDTO.getContent().getSchemeIds().isEmpty()){
        
        } else {
            if (0 == reqDTO.getContent().getSchemeIds().get(0)) {
                User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
                RiskMonitor m = new RiskMonitor();
                m.setStatus(Constant.DEFAULT_STATUS_NORMAL);
                m.setCreateUserId(loginUser.getId());
                compIds.addAll(monitorService.queryList(m).stream().map(r -> r.getCompId()).collect(Collectors.toList()));
                CompDept dept = new CompDept();
                dept.setDeptId(loginUser.getDeptId());
                compIds.addAll(compDeptService.queryList(dept).stream().map(c -> c.getCompId()).collect(Collectors.toList()));
                if (compIds.isEmpty()) {
                    return new ResponseInfo<>(page);
                }
            } else {
                for (Long schemeId : reqDTO.getContent().getSchemeIds()) {
                    RiskMonitor m = new RiskMonitor();
                    m.setSchemeId(schemeId);
                    m.setStatus(Constant.DEFAULT_STATUS_NORMAL);
                    RiskSchemeConfig config = new RiskSchemeConfig();
                    config.setTagClass(Constant.DEFAULT_STATUS_DELETE);
                    config.setSchemeId(schemeId);
                    tagIds.addAll(configService.queryList(config).stream().map(c -> c.getTagId()).collect(Collectors.toList()));
                    compIds.addAll(monitorService.queryList(m).stream().map(monitor -> monitor.getCompId()).collect(Collectors.toList()));
                }
                if (tagIds.isEmpty()){
                    return new ResponseInfo<>(page);
                }
            }
            
        }
        
        ListRiskTypeReqDTO dto = new ListRiskTypeReqDTO();
        BeanUtils.copyProperties(reqDTO.getContent(),dto);
        QueryParticularsDTO query = new QueryParticularsDTO();
        query.setCompIds(compIds);
        query.setTagIds(tagIds);
        query.setRiskClass(reqDTO.getContent().getRiskClass());
        
        query.setRiskLevel(reqDTO.getContent().getRiskLevels());
        query.setStartTime(DateUtils.format(reqDTO.getContent().getStartTime(),DateUtils.DATE));
        query.setEndTime(DateUtils.format(reqDTO.getContent().getEndTime(),DateUtils.DATE));
        query.setCompName(reqDTO.getContent().getCompName());
        page = pageService
                .page(reqDTO.getPageParam(), () -> compRiskService.queryParticulars(query));
        List<ListRiskRespDTO> collect = page.getRows().stream().distinct().collect(Collectors.toList());
        collect.forEach(c->{
            if (null != c.getRiskContent()){
                String aNull = c.getRiskContent().replaceAll("null", "-");
                c.setRiskContent(aNull);
            }
            if (null != c.getRiskNote()){
                String aNull = c.getRiskNote().replaceAll("null", "");
                c.setRiskNote(aNull);
            }
        });
        page.setRows(collect);
        String scheme="";
        if (reqDTO.getContent().getSchemeIds().isEmpty()){
            scheme="全部";
        }else if(0 == reqDTO.getContent().getSchemeIds().get(0)){
            scheme="全部监控公司";
        }else {
            for (Long s : reqDTO.getContent().getSchemeIds()) {
                scheme = scheme+ schemeService.queryById(s).getName()+" ";
            }
        }
        Map<String, Dict> riskClass = dictService.queryDict("RISK_CLASS");
        Map<String, Dict> riskLevel = dictService.queryDict("RISK_LEVEL");
        
        String c= "";
        
        for (Integer i : reqDTO.getContent().getRiskClass()) {
            c = c+riskClass.get(i.toString()).getBusiName()+" ";
        }
        String l ="";
        for (Integer level : reqDTO.getContent().getRiskLevels()) {
            l=l+riskLevel.get(level.toString()).getBusiName()+" ";
        }
    
    
        OptLogReqVO vo = new OptLogReqVO();
        vo.setStatus(1);
        vo.setOptModule(6);
        vo.setOptType(3);
        vo.setOptContent("检索风险动态，监控方案:【"+scheme+"】+风险类型:【"+c+"】+风险级别:【"+l+"】+时间筛选：:【"+DateUtils.format(reqDTO.getContent().getStartTime(),DateUtils.DATE)+DateUtils.format(reqDTO.getContent().getEndTime(),DateUtils.DATE)+"】+关键字:【"+reqDTO.getContent().getCompName()+"】");
        logService.saveOptLog(vo);
        
        return new ResponseInfo<>(page);
    }
    
    @ApiOperation("下载风险预警详情")
    @DownloadMapping("/down-risk-particulars")
    public void downRiskParticulars(@ApiParam("请求参数") @Valid ListRiskReqVO reqDTO, HttpServletResponse response)
            throws Exception {
        Long aa = System.currentTimeMillis();
        List<Long> compIds = new ArrayList<>();
        List<Long> tagIds = new ArrayList<>();
        List<ListRiskRespDTO> result = new ArrayList<>();
        Map<String, Dict> riskClass = dictService.queryDict("RISK_CLASS");
        Map<String, Dict> riskLevel = dictService.queryDict("RISK_LEVEL");
        if(reqDTO.getSchemeIds().isEmpty()){
        
        } else  if (0 == reqDTO.getSchemeIds().get(0)){
            
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            RiskMonitor m = new RiskMonitor();
            m.setStatus(Constant.DEFAULT_STATUS_NORMAL);
            m.setCreateUserId(loginUser.getId());
            compIds.addAll(monitorService.queryList(m).stream().map(r->r.getCompId()).collect(Collectors.toList()));
            CompDept dept = new CompDept();
            dept.setDeptId(loginUser.getDeptId());
            compIds.addAll(compDeptService.queryList(dept).stream().map(c->c.getCompId()).collect(Collectors.toList()));
            log.error(loginUser.getUserCode()+"监控公司数量"+compIds.size());
            if(compIds.isEmpty()){
                excelDownloadSevice.excelDownload(result, response, "默认客户监控列表");
                return;
            }
        } else {
            for (Long schemeId : reqDTO.getSchemeIds()) {
                RiskMonitor m = new RiskMonitor();
                m.setSchemeId(schemeId);
                m.setStatus(Constant.DEFAULT_STATUS_NORMAL);
                RiskSchemeConfig config = new RiskSchemeConfig();
                config.setTagClass(Constant.DEFAULT_STATUS_DELETE);
                config.setSchemeId(schemeId);
                tagIds.addAll(configService.queryList(config).stream().map(c->c.getTagId()).collect(Collectors.toList()));
                compIds.addAll(monitorService.queryList(m).stream().map(monitor->monitor.getCompId()).collect(Collectors.toList()));
            }
        }
    
        ListRiskTypeReqDTO dto = new ListRiskTypeReqDTO();
        BeanUtils.copyProperties(reqDTO,dto);
        QueryParticularsDTO query = new QueryParticularsDTO();
        query.setCompIds(compIds);
        query.setTagIds(tagIds);
        query.setRiskClass(reqDTO.getRiskClass());
    
        query.setRiskLevel(reqDTO.getRiskLevels());
        query.setStartTime(DateUtils.format(reqDTO.getStartTime(),DateUtils.DATE));
        query.setEndTime(DateUtils.format(reqDTO.getEndTime(),DateUtils.DATE));
        query.setCompName(reqDTO.getCompName());
        System.out.println(System.currentTimeMillis() - aa + "aa");
        List<ListRiskRespDTO> collect = compRiskService.queryDownParticulars(query).stream().distinct().collect(Collectors.toList());
        System.out.println(System.currentTimeMillis() - aa + "bb");
        collect.forEach(c->{
            long v= System.currentTimeMillis();
            if (c.getRiskClass() != null) {
                c.setRiskClassMessage(riskClass.get(c.getRiskClass().toString()).getBusiName());
                System.out.println(System.currentTimeMillis()-v+"class");
            }
            
            if(c.getRiskLevel() != null){
                v = System.currentTimeMillis();
                c.setRiskLevelMessage(riskLevel.get(c.getRiskLevel().toString()).getBusiName());
                System.out.println(System.currentTimeMillis()-v+"level");
            }
        
            if (null != c.getRiskContent() && -1 !=  c.getRiskContent().indexOf("null")){
                v = System.currentTimeMillis();
                String aNull = c.getRiskContent().replaceAll("null", "-");
                c.setRiskContent(aNull);
                System.out.println(System.currentTimeMillis()-v+"content");
            }
            v = System.currentTimeMillis();
            c.setTime(DateUtils.format(c.getBuildTime(),DateUtils.DATE));
            System.out.println(System.currentTimeMillis()-v+"time");
            result.add(c);
        });
        if (result.isEmpty()){
            result.add(new ListRiskRespDTO());
        }
    
        OptLogReqVO vo = new OptLogReqVO();
        vo.setStatus(1);
        vo.setOptModule(6);
        vo.setOptType(11);
        vo.setOptContent("导出风险动态列表");
        logService.saveOptLog(vo);
        
        excelDownloadSevice.excelDownload(result, response, "风险详情列表");
        
    }
    
    @ApiOperation("新闻舆情")
    @PostMapping("/list-risk-news")
    public ResponseInfo<PageResult<ListNewsRespVO>> listRiskNews(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<ListRiskNewsReqVO> reqDTO){
        PageResult<ListNewsRespVO> pageResult = riskCompService.listRiskNews(reqDTO);
        String scheme="";
        if (reqDTO.getContent().getSchemeIds().isEmpty()){
            scheme="全部";
        }else if(0 == reqDTO.getContent().getSchemeIds().get(0)){
            scheme="全部监控公司";
        }else {
            for (Long s : reqDTO.getContent().getSchemeIds()) {
                scheme = scheme+ schemeService.queryById(s).getName()+" ";
            }
        }
        
        String s = "";
    
        for (Integer i : reqDTO.getContent().getSentiments()) {
            if (i == 1){
                s= s+"积极"+" ";
            }
            if(i==2){
                s= s+"中立"+" ";
            }
            
            if (i==3){
                s= s+"消极"+" ";
            }
        }
        
        
        OptLogReqVO vo = new OptLogReqVO();
        vo.setStatus(1);
        vo.setOptModule(6);
        vo.setOptType(3);
        String t ="";
        if(reqDTO.getContent().getTitle()!=null){
            t=reqDTO.getContent().getTitle();
        }
        vo.setOptContent("检索輿情动态，监控方案:【"+scheme+"】+情感类别:【"+s+"】+时间筛选：:【"+reqDTO.getContent().getStartTime()+reqDTO.getContent().getEndTime()+"】+关键字:【"+t+"】");
        logService.saveOptLog(vo);
        return new ResponseInfo<>(pageResult);
    }
    
    @ApiOperation("风险首页")
    @PostMapping("/risk-home-page")
    public ResponseInfo<RiskHomePageRespVO> riskHomePage(@ApiParam("请求参数") @Valid @RequestBody RiskHomePageReqVO vo){
        RiskHomePageRespVO respVO = new RiskHomePageRespVO();
        
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CompDept dept = new CompDept();
        dept.setDeptId(loginUser.getDeptId());
        List<Long> collect = compDeptService.queryList(dept).stream().map(c -> c.getCompId())
                .collect(Collectors.toList());
        RiskMonitor monitor = new RiskMonitor();
        if (vo.getSchemeId()!= 0 && null != vo.getSchemeId()){
            monitor.setSchemeId(vo.getSchemeId());
        }
        
        monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        monitor.setCreateUserId(loginUser.getId());
        List<Long> compIds = monitorService.queryList(monitor).stream().map(m -> m.getCompId())
                .collect(Collectors.toList());
        compIds.addAll(collect);
        respVO.setComp(compIds.size());//统计监控公司数量
        
        if (compIds.isEmpty()){
            respVO.setManagement(0L);
            respVO.setJudicial(0L);
            respVO.setBusiness(0L);
            return new ResponseInfo<>(respVO);
        }
        log.info("返回的公司数："+respVO.getComp());
        if (vo.getCompId() != null&& vo.getCompId() != 0 ){
            if (compIds.contains(vo.getCompId())){
                compIds=Collections.singletonList(vo.getCompId());
            }else {
                respVO.setManagement(0L);
                respVO.setJudicial(0L);
                respVO.setBusiness(0L);
                return new ResponseInfo<>(respVO);
            }
        }
        
        RiskTimeDTO dto = new RiskTimeDTO();
        dto.setIds(compIds);
        String beginTime=null;
        String endTime=null;
        //查询时间类型 0全部 1当天 2最近7天 3最近一个月 4自定义home-page-dynamic
        if (Constant.COMP_RISK_TIME_DAY.equals(vo.getTimeType())) {
            beginTime = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(vo.getTimeType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(vo.getTimeType())) {
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(),0 ), DatePattern.NORM_DATE_PATTERN);
        } else if (Constant.COMP_RISK_TIME_DEFINE.equals(vo.getTimeType())) {
            if (null == vo.getStartTime() || null == vo.getEndTime()) {
                throw new ElkException(ElkErrorType.ELK_SEARCH_DATE_NULL);
            }
            beginTime = DateUtil.format(vo.getStartTime(), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtils.format(vo.getEndTime(),DateUtils.DATE);
        }
        dto.setStartTime(beginTime);
        dto.setEndTime(endTime);
        respVO.setBusiness(compRiskService.countBusinessByCompIds(dto));
        respVO.setJudicial(compRiskService.countJudicialByCompIds(dto));
        respVO.setManagement(compRiskService.countManagementByCompIds(dto));
        return new ResponseInfo(respVO);
    }
    
    @ApiOperation("首页风险")
    @PostMapping("/home-page-risk")
    public ResponseInfo<HomePageRiskRespVO> homePageRisk(@ApiParam("请求参数") @Valid @RequestBody HomePageRiskReqVO vo ){
        HomePageRiskRespVO respVO = riskCompService.homePageRisk(vo);
        return  new ResponseInfo(respVO);
    }
    @ApiOperation("公司画像负面舆情")
    @PostMapping("/comp-risk")
    public ResponseInfo<CompRiskVO> compRisk(@ApiParam("请求参数") @Valid @RequestBody QueryCompMonitorReqVO vo){
        CompRiskVO compRiskVO = new CompRiskVO();
        
        compRiskVO.setTips(riskTypeService.countTipsByComp(vo.getCompId()));//提示风险
        compRiskVO.setCommonly(riskTypeService.countCommonlyByComp(vo.getCompId()));//统计一般风险
        compRiskVO.setMore(riskTypeService.countMoreByComp(vo.getCompId()));//统计较大风险
        compRiskVO.setSerious(riskTypeService.countSeriousByComp(vo.getCompId()));//统计严重风险
        compRiskVO.setPositive(appNewsSentimentService.countPositiveByComp(vo.getCompId().toString()));//统计积极
        compRiskVO.setNegative(appNewsSentimentService.countNegativeByComp(vo.getCompId().toString()));//统计消极
        compRiskVO.setNeutral(appNewsSentimentService.countNeutralByComp(vo.getCompId().toString()));//统计中立
        compRiskVO.setRiskType(riskTypeService.queryByIds(vo.getCompId()).size());
        compRiskVO.setList(riskTypeService.queryCompType(vo.getCompId()));
        AppNewsSentiment appNewsSentiment = new AppNewsSentiment();
        appNewsSentiment.setCompId(vo.getCompId().toString());
        appNewsSentiment.setSentiment(Constant.SENTIMENT_NEGATIVE);
        List<AppNews> news = newsService.queryCompNews(vo.getCompId().toString());
        if(news.size() >20){
            news = news.subList(0,20);
        }
        compRiskVO.setContent(news);
        
        return  new ResponseInfo<CompRiskVO>(compRiskVO);
    }
    
    @ApiOperation("首页新闻轮播图")
    @PostMapping("/home-page-news-carousel")
    public ResponseInfo<HomePageNewsCarouselVRespVO> homePageNewsCarousel(){
        HomePageNewsCarouselVRespVO vo = new HomePageNewsCarouselVRespVO();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        RiskMonitor monitor = new RiskMonitor();
        monitor.setCreateUserId(loginUser.getId());
        monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        List<String> compIds = riskMonitorService.queryList(monitor).stream().map(r -> r.getCompId().toString())
                .collect(Collectors.toList());
        compIds.addAll(compDeptService.queryByDept(loginUser.getDeptId()).stream().map(comp->comp.toString()).collect(Collectors.toList()));
        List<AppNews> appNews = new ArrayList<>();
        if (compIds.isEmpty()){
            vo.setAppNews(appNews);
            return new ResponseInfo(vo);
        }
        
       String  beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
       String  endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
         appNews = newsService.queryByComps(compIds,beginTime,endTime);
        List<AppNews> dayNews = appNews.stream().filter(a -> {
            if (DateUtils.format(a.getPublishTime(), DateUtils.DATE)
                    .equals(DateUtils.format(new Date(), DateUtils.DATE))) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        if (dayNews.size()>5){
            appNews=dayNews;
        }
        vo.setAppNews(appNews);
        return new ResponseInfo(vo);
    }
    
    @ApiOperation("风险首页等级")
    @PostMapping("/risk-home-page-level")
    public ResponseInfo<List<RiskHomePageLevelVO>> riskHomePageLevel(@ApiParam("请求参数") @Valid @RequestBody RiskHomePageReqVO  reqDTO){
    
        List<RiskHomePageLevelVO> riskHomePageLevelVOS = riskCompService.riskHomePageLevel(reqDTO);
        return new ResponseInfo<List<RiskHomePageLevelVO>>(riskHomePageLevelVOS);
    }
    
    @ApiOperation("首页风险趋势")
    @PostMapping("/home-page-trend")
    public ResponseInfo<RiskTrendVO> homePageTrend(@ApiParam("请求参数") @Valid @RequestBody RiskHomePageReqVO vo){
        RiskTrendVO trendVOS = riskCompService.homePageTrend(vo);
        return new ResponseInfo<RiskTrendVO>(trendVOS);
    }
    
    @ApiOperation("风险首页公司")
    @PostMapping("/home-page-comp")
    public ResponseInfo<List<RiskHomePageCompRespVO>> riskHomePageComp(){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        List<RiskHomePageCompRespVO> list = new ArrayList<>();
        List<QueryHomePageCompDTO> dtos = compRiskService.queryCompId(loginUser.getId());
        List<QueryHomePageCompDTO> dtos1 = compDeptService.queryByDeptId(loginUser.getDeptId());
        dtos.addAll(dtos1);
        List<QueryHomePageCompDTO> collect = dtos.stream()
                .sorted(Comparator.comparing(QueryHomePageCompDTO::getCreateTime).reversed()).limit(5).collect(Collectors.toList());
        for (QueryHomePageCompDTO queryHomePageCompDTO : collect) {
            RiskHomePageCompRespVO respVO = new RiskHomePageCompRespVO();
            respVO.setCompId(queryHomePageCompDTO.getCompId());
            respVO.setCompName(queryHomePageCompDTO.getCompName());
            respVO.setCommonly(riskTypeService.countCommonlyByComp(queryHomePageCompDTO.getCompId()));//统计一般风险
    
            respVO.setTips(riskTypeService.countTipsByComp(queryHomePageCompDTO.getCompId()));//统计提示风险
    
            respVO.setMore(riskTypeService.countMoreByComp(queryHomePageCompDTO.getCompId()));//统计较大风险
    
            respVO.setSerious(riskTypeService.countSeriousByComp(queryHomePageCompDTO.getCompId()));//统计严重风险
            
            list.add(respVO);
        }
        
        return new ResponseInfo<>(list);
    }
    
    @ApiOperation("风险新闻公司")
    @PostMapping("/home-news-comp")
    public ResponseInfo<List<RiskHomeNewsCompRespVO>> homeNewsComp(){
        List<RiskHomeNewsCompRespVO> list = new ArrayList<>();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        List<QueryHomePageCompDTO> dtos = compRiskService.queryCompId(loginUser.getId());
        List<QueryHomePageCompDTO> dtos1 = compDeptService.queryByDeptId(loginUser.getDeptId());
        dtos.addAll(dtos1);
        List<QueryHomePageCompDTO> collect = dtos.stream()
                .sorted(Comparator.comparing(QueryHomePageCompDTO::getCreateTime)).limit(5).collect(Collectors.toList());
    
        for (QueryHomePageCompDTO query : collect) {
            RiskHomeNewsCompRespVO vo = new RiskHomeNewsCompRespVO();
            vo.setCompId(query.getCompId());
            vo.setCompName(query.getCompName());
            vo.setNegative(appNewsSentimentService.countNegativeByComp(query.getCompId().toString()));
            vo.setNeutral(appNewsSentimentService.countNeutralByComp(query.getCompId().toString()));
            vo.setPositive(appNewsSentimentService.countPositiveByComp(query.getCompId().toString()));
            list.add(vo);
        }
        
        return new ResponseInfo(list);
    }
    
    @ApiOperation("风险首页动态")
    @PostMapping("/home-page-dynamic")
    public ResponseInfo<List<HomePageDynamicRespVO>> homePageDynamic(){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        RiskMonitor monitor = new RiskMonitor();
        monitor.setCreateUserId(loginUser.getId());
        monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        List<Long> compIds = riskMonitorService.queryList(monitor).stream().map(r -> r.getCompId())
                .collect(Collectors.toList());
        compIds.addAll(compDeptService.queryByDept(loginUser.getDeptId()));
        if (compIds.isEmpty()){
            return new ResponseInfo<>(new ArrayList<>());
        }
        
        List<HomePageDynamicRespVO> compRisks = compRiskService.queryListCompRisk(compIds);
        return new ResponseInfo<List<HomePageDynamicRespVO>>(compRisks);
    }
    
    
    
    
    @ApiOperation("新闻首页")
    @PostMapping("/home-page-news")
    public ResponseInfo<HomePageNewsRespVO> homePageNews(@ApiParam("请求参数") @Valid @RequestBody RiskHomePageReqVO vo){
        HomePageNewsRespVO respVO = riskCompService.homePageNews(vo);
        
        return new ResponseInfo<HomePageNewsRespVO>(respVO);
    }
    
   
   
    @ApiOperation("查询公司对应的风险")
    @PostMapping("/query-comp-risk")
    public ResponseInfo<PageResult<QueryByRiskTypeRespDTO>> queryCompRisk(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<QueryCompRiskReqVO> dto){
        PageResult<QueryByRiskTypeRespDTO> page =  riskCompService.queryListByRiskType(dto);
        return new ResponseInfo<>(page);
    }
    
    @ApiOperation("查询公司对应的风险类型")
    @PostMapping("/query-comp-risk-type")
    public ResponseInfo<QueryCompRiskTypeRespVO> queryCompRiskType(@ApiParam("请求参数") @Valid @RequestBody QueryByCompIdVO vo){
        QueryCompRiskTypeRespVO respVO = new QueryCompRiskTypeRespVO();
        respVO.setRed(compRiskService.countRed(vo.getCompId()));
        
        respVO.setYellow(compRiskService.countYellow(vo.getCompId()));
        
        respVO.setRedRiskType(compRiskService.redRiskType(vo.getCompId()));
        
        respVO.setYellowRiskType(compRiskService.yellowRiskType(vo.getCompId()));
        
        return new ResponseInfo<QueryCompRiskTypeRespVO>(respVO);
    }
    
    @ApiOperation("查询公司对应的新闻")
    @PostMapping("/query-comp-news")
    public ResponseInfo<PageResult<ListNewsRespVO>> queryCompNews(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<QueryCompNewsReqVO> dto){
        PageResult<ListNewsRespVO> pageResult = riskCompService.queryCompNews(dto);
        return new ResponseInfo<PageResult<ListNewsRespVO>>(pageResult);
    }
    
    @ApiOperation("查询公司关联风险")
    @PostMapping("/query-comp-associate-risk")
    public ResponseInfo<List<QueryCompAssociateDTO>> queryCompAssociateRisk(@ApiParam("请求参数") @Valid @RequestBody ReqDTO<QueryCompAssociateRiskReqVO> dto){
        List<QueryCompAssociateDTO> dtoList = riskCompService.queryCompAssociateRisk(dto);
        
        return new ResponseInfo(dtoList);
    }
    
    
    @ApiOperation("首页新闻舆情趋势")
    @PostMapping("/home-page-news-trend")
    public ResponseInfo<List<HomePageNewsTrendVO>> homePageNewsTrend(@ApiParam("请求参数") @Valid @RequestBody RiskHomePageReqVO vo){
        List<HomePageNewsTrendVO> list = riskCompService.homePageNewsTrend(vo);
        return new ResponseInfo<List<HomePageNewsTrendVO>>(list);
    }
    
    @ApiOperation("查询公司是否被监控")
    @PostMapping("query-comp-monitor")
    public ResponseInfo<QueryCompMonitorRespVO> queryCompMonitor(@ApiParam("请求参数") @Valid @RequestBody QueryCompMonitorReqVO vo){
        RiskMonitor monitor = new RiskMonitor();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        monitor.setUpdateUserId(loginUser.getId());
        monitor.setCompId(vo.getCompId());
        List<RiskMonitor> riskMonitors = riskMonitorService.queryList(monitor);
        QueryCompMonitorRespVO respVO = new QueryCompMonitorRespVO();
        if(companyService.queryById(vo.getCompId()) == null){
            return new ResponseInfo("1","该公司不存在");
        }
        BeanUtils.copyProperties(companyService.queryById(vo.getCompId()),respVO);
        if (riskMonitors.isEmpty()){
            respVO.setStatus(Constant.DEFAULT_STATUS_DELETE);
        }else {
            respVO.setStatus(riskMonitors.get(0).getStatus());
        }
        if (null !=respVO.getLogo() && !respVO.getLogo().isEmpty() ){
            respVO.setLogo(minioAddress + respVO.getLogo());
        }
        TagRel tagRel = new TagRel();
        tagRel.setDataType(Constant.TAG_DATATYPE_COMP);
        tagRel.setDataId(vo.getCompId().toString());
        tagRel.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        List<TagRel> tagRels = tagRelService.queryList(tagRel);
        respVO.setLabels(tagRels);
        return new ResponseInfo<> (respVO);
    }
    
    @ApiOperation("默认客户监控列表")
    @PostMapping("/default-monitor-list")
    public ResponseInfo<PageResult<DefaultMonitorListRespVO>> defaultMonitorList(@ApiParam("请求参数") @RequestBody  ReqDTO reqDTO){
        List<DefaultMonitorListRespVO> list =new ArrayList<>();
        PageResult<DefaultMonitorListRespVO> pageResult = new PageResult<>();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        
        List<Long> compIds = compDeptService.queryByDept(loginUser.getDeptId());
        if (compIds.isEmpty()){
            return new ResponseInfo(pageResult);
        }
        List<DefaultMonitorListDTO> risk = compDeptService.queryCompByDeptId(loginUser.getDeptId());
        
        List<String> news = compIds.stream().map(c -> c.toString()).collect(Collectors.toList());
        List<DefaultMonitorListDTO> appNewsSentiments = appNewsSentimentService.queryByDept(news);
        appNewsSentiments.forEach(a->{
            a.setCompId(Long.parseLong(a.getNewsCompId()));
        });
        risk.addAll(appNewsSentiments);
        log.info(loginUser.getUserCode()+"机构客户：：：：" + risk.size());
        Map<String,DefaultMonitorListDTO> map = new HashMap<>();
        for (DefaultMonitorListDTO dto : risk) {
            
            DefaultMonitorListDTO monitorListDTO = map.get(dto.getCompName());
            if (monitorListDTO == null){
                
                map.put(dto.getCompName(),dto);
            }else {
                log.info("机构客户公司名"+monitorListDTO.getNews()+"<<<<"+monitorListDTO.getRisk());
                if (dto.getNews() != null && monitorListDTO.getNews() == null){
                    monitorListDTO.setNews(dto.getNews());
                }
                if (dto.getRisk() != null && monitorListDTO.getRisk() == null){
                    monitorListDTO.setRisk(dto.getRisk());
                }
                if (dto.getTime() != null && monitorListDTO.getTime()==null){
                    monitorListDTO.setTime(dto.getTime());
                }
                else if (dto.getTime() == null && monitorListDTO.getTime()==null){
                    monitorListDTO.setTime(dto.getTime());
                }
                else if (dto.getTime() == null && monitorListDTO.getTime()!=null){
                    monitorListDTO.setTime(monitorListDTO.getTime());
                }
                else if (dto.getTime().compareTo(monitorListDTO.getTime()) != -1){
                    monitorListDTO.setTime(dto.getTime());
                }
            }
        }
        for (Map.Entry<String, DefaultMonitorListDTO> entity : map.entrySet()) {
            DefaultMonitorListRespVO vo = new DefaultMonitorListRespVO();
            BeanUtils.copyProperties(entity.getValue(),vo);
            list.add(vo);
        }
        List<DefaultMonitorListRespVO> sortList = list.stream().sorted(Comparator.comparing(
                DefaultMonitorListRespVO::getTime,Comparator.nullsFirst(Date::compareTo)).reversed()).collect(Collectors.toList());
        ListUtil<DefaultMonitorListRespVO> listUtil = BeanUtils.instantiateClass(ListUtil.class);
        pageResult= listUtil.listPage(reqDTO.getPageParam(), sortList);
        return new ResponseInfo(pageResult);
    }
    
    
    @ApiOperation("下载默认客户列表")
    @DownloadMapping("/down-default-list")
    public void qhRcnclQueryExcel(HttpServletResponse response) throws Exception {
        log.info("导出默认监控列表............");
        OptLogReqVO vo1 = new OptLogReqVO();
        vo1.setStatus(1);
        vo1.setOptModule(6);
        vo1.setOptType(11);
        vo1.setOptContent("导出默认监控列表");
        logService.saveOptLog(vo1);
        List<DefaultMonitorListRespVO> list =new ArrayList<>();
        PageResult<DefaultMonitorListRespVO> pageResult = new PageResult<>();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        List<ExcelDownDefaultListVO> result = new ArrayList<>();
        List<Long> compIds = compDeptService.queryByDept(loginUser.getDeptId());
        if (compIds.isEmpty()){
            ExcelDownDefaultListVO vo = new ExcelDownDefaultListVO();
            result.add(vo);
            excelDownloadSevice.excelDownload(result, response, "默认客户监控列表");
            return;
        }
        List<DefaultMonitorListDTO> risk = compDeptService.queryCompByDeptId(loginUser.getDeptId());
    
        List<String> news = compIds.stream().map(c -> c.toString()).collect(Collectors.toList());
        List<DefaultMonitorListDTO> appNewsSentiments = appNewsSentimentService.queryByDept(news);
        appNewsSentiments.forEach(a->{
            a.setCompId(Long.parseLong(a.getNewsCompId()));
        });
        risk.addAll(appNewsSentiments);
        log.info(loginUser.getUserCode()+"机构客户：：：：" + risk.size());
        Map<String,DefaultMonitorListDTO> map = new HashMap<>();
        for (DefaultMonitorListDTO dto : risk) {
        
            DefaultMonitorListDTO monitorListDTO = map.get(dto.getCompName());
            if (monitorListDTO == null){
            
                map.put(dto.getCompName(),dto);
            }else {
                log.info("机构客户公司名"+monitorListDTO.getNews()+"<<<<"+monitorListDTO.getRisk());
                if (dto.getNews() != null && monitorListDTO.getNews() == null){
                    monitorListDTO.setNews(dto.getNews());
                }
                if (dto.getRisk() != null && monitorListDTO.getRisk() == null){
                    monitorListDTO.setRisk(dto.getRisk());
                }
                if (dto.getTime() != null && monitorListDTO.getTime()==null){
                    monitorListDTO.setTime(dto.getTime());
                }
                else if (dto.getTime() == null && monitorListDTO.getTime()==null){
                    monitorListDTO.setTime(dto.getTime());
                }
                else if (dto.getTime() == null && monitorListDTO.getTime()!=null){
                    monitorListDTO.setTime(monitorListDTO.getTime());
                }
                else if (dto.getTime().compareTo(monitorListDTO.getTime()) != -1){
                    monitorListDTO.setTime(dto.getTime());
                }
            }
        }
        for (Map.Entry<String, DefaultMonitorListDTO> entity : map.entrySet()) {
            DefaultMonitorListRespVO vo = new DefaultMonitorListRespVO();
            BeanUtils.copyProperties(entity.getValue(),vo);
            list.add(vo);
        }
        List<DefaultMonitorListRespVO> sortList = list.stream().sorted(Comparator.comparing(
                DefaultMonitorListRespVO::getTime,Comparator.nullsFirst(Date::compareTo)).reversed()).collect(Collectors.toList());
        // 根据条件查询，导出。只有整体导出
       
        
        if ( !list.isEmpty()) {//核算赋值
            // 导出 列表数据赋值
            for (DefaultMonitorListRespVO vo : sortList) {
                ExcelDownDefaultListVO excel = new ExcelDownDefaultListVO();
                BeanUtils.copyProperties(vo,excel);
                if (excel.getNews() == null){
                    excel.setNews(0L);
                }
                if (excel.getRisk() == null){
                    excel.setRisk(0L);
                }
                excel.setTime(DateUtils.format(vo.getTime(),DateUtils.DATE));
                result.add(excel);
            }
        }
        if (result.isEmpty()){
            result.add(new ExcelDownDefaultListVO());
        }
        
       
        
        // 导出汇总及明细结果数据
        excelDownloadSevice.excelDownload(result, response, "默认客户监控列表");
        }
    
}
